The blog of dlaa.me

Posts tagged "Windows Phone Toolkit"

"And she'd say, 'Can you see ... what I'm saying?'" [How to: Localize a Windows Phone 7 application that uses the Windows Phone Toolkit into different languages]

While it might be convenient if everybody spoke the same language (or communicated via telepathy), that's not the world we live in. :) Therefore, building applications that can be easily translated to other languages is an important consideration. Fortunately, it's easy - and it's covered in the MSDN article How to: Build a Localized Application for Windows Phone. But what's not covered is how to localize the controls in the Silverlight for Windows Phone Toolkit. As you might expect, it's fairly similar, but I've had a few people ask about this explicitly and I decided to do a quick post on the topic. As long as I was at it, I figured I'd show the entire process from start to finish just to make things a little easier...

 

Prepare the emulator/phone

In order to monitor our progress as the sample application gets localized, it's helpful to work in a non-default language which makes it easy to identify the un-localized parts. I run an English operating system, so I'll use Spanish for this example:

  1. Open the Settings application

  2. Choose region & language

  3. Open the Display language picker

  4. Change to "Español"

  5. Tap the link to restart the emulator/phone:

    Settings

 

Create a new application

We'll start with a brand new application using the default template provided by the Visual Studio 2010 development tools:

  1. From the File menu, choose New, then Project...

  2. Go to the "Silverlight for Windows Phone" section and create a "Windows Phone Application" with the name of your choice

  3. From the Project menu, choose Add New Item...

  4. Select "Resources File" and name it AppResources.resx

  5. Add an entry for Name="Title" and Value="welcome"

  6. Open MainPage.xaml.cs and add the following to the end of the constructor to set the text of the existing PageTitle element:

    PageTitle.Text = AppResources.Title;
  7. Run the application to see the custom title in English:

    New application

 

Localize the application

Now let's localize the sample application so it uses the proper language for the user's settings. In the steps below, we'll add support for Spanish (via the "es" language code), but adding other languages is a simple matter of repeating these steps using the other language's code and translations. It's a little bit of effort, but it's all quite simple:

  1. In the Solution Explorer window, select AppResources.resx by clicking on it

  2. Press Ctrl+C, then Ctrl+V to create a copy of AppResources.resx

  3. Select Copy of AppResources.resx and press F2 to rename it to AppResources.es.resx

  4. Staying in the Solution Explorer window, right-click the project root node and choose Unload Project

  5. Right-click the project node again and choose Edit [ProjectName].csproj

  6. Change the existing SupportedCultures element to be:

    <SupportedCultures>es</SupportedCultures>
  7. Back in the Solution Explorer window, right-click the project node and choose Reload Project

  8. Open AppResources.es.resx and change "welcome" to "bienvenido"

  9. Run the application and verify the custom title now shows up in Spanish (no code changes necessary!):

    Localized application

 

Add the Windows Phone Toolkit project

Now we'll modify the sample application to reference the Windows Phone Toolkit. (You can read more about the Windows Phone Toolkit in my introductory post.) Rather than adding a binary reference to the Toolkit, we'll add a project reference and build the Toolkit code as part of the sample application (for reasons that will become clear soon):

  1. Go to http://silverlight.codeplex.com/ and download the "Silverlight for Windows Phone Toolkit Source & Sample" ZIP file

  2. Unblock the ZIP file (see the notes at the end of this post for instructions)

  3. Right-click the ZIP file and choose Extract All... to extract all files to the directory of your choice

  4. From the File menu in Visual Studio, choose Add, then Existing Project...

  5. Choose the Microsoft.Phone.Controls.Toolkit.csproj file found in the same-named directory of the extracted content

  6. Click on the application project node in Solution Explorer to make it active again

  7. From the Project menu, choose Add Reference...

  8. Switch to the Projects tab and pick the Microsoft.Phone.Controls.Toolkit project

  9. Press F6 and verify the solution builds both projects successfully:

    ------ Build started: Project: Microsoft.Phone.Controls.Toolkit, Configuration: Debug Any CPU ------
    ...
    ------ Build started: Project: LocalizedPhoneApplicationWithToolkit, Configuration: Debug Any CPU ------
    ...
    ========== Build: 2 succeeded or up-to-date, 0 failed, 0 skipped ==========

 

Add some Windows Phone Toolkit controls

Now it's time to add two of those handy-dandy Windows Phone Toolkit controls (both covered in the aforementioned blog post): DatePicker and ToggleSwitch. We'll follow the usual steps for referencing third-party controls which should be pretty familiar to everyone:

  1. Open MainPage.xaml and switch to XAML view

  2. Add the following to the top of the file along with the other xmlns definitions:

    xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
  3. Paste the following inside the empty "ContentPanel" Grid:

    <StackPanel>
        <toolkit:DatePicker/>
        <toolkit:ToggleSwitch/>
    </StackPanel>
  4. Optional: Follow the steps in the notes of my Windows Phone Toolkit introduction to add the DatePicker Application Bar icons to the project

  5. Run the application to see the text of the Toolkit controls in English:

    Toolkit ToggleSwitch Toolkit DatePicker

    Note: The day and month names are already in Spanish because they come from the operating system which knows to use the current language for dates. The Spanish-correct day/month/year formatting (vs. the United States default of month/day/year) is automatically provided by the DatePicker control.

 

Localize the Windows Phone Toolkit controls

Finally, we'll localize the Toolkit controls using the same process we did for the sample application itself:

  1. In Solution Explorer, expand the "Properties" folder for the Toolkit and click Resources.resx

  2. Press Ctrl+C, then Ctrl+V to create a copy of Resources.resx

  3. Select Copy of Resources.resx and press F2 to rename it to Resources.es.resx

  4. Open Resources.es.resx and change "CHOOSE DATE" to "ELIGE UNA FECHA", "cancel" to "cancelar", "done" to "listo", "Off" to "Desactivado", and "On" to "Activado"

  5. Run the application and verify the Toolkit control text is also in Spanish now:

    Localized Toolkit ToggleSwitch Localized Toolkit DatePicker

    Note: If you get the error Unable to copy file "obj\Debug\Microsoft.Phone.Controls.Toolkit.dll" to "..\Bin\Debug\Microsoft.Phone.Controls.Toolkit.dll". The process cannot access the file '..\Bin\Debug\Microsoft.Phone.Controls.Toolkit.dll' because it is being used by another process. when compiling, close all documents in Visual Studio via Window/Close All Documents, then restart Visual Studio itself.

 

At the end of the day, translating an application isn't just a nice thing to do, it's good business! We operate in a global marketplace and that means localized products can have a big advantage over their single-language-only competitors. While good localization can't save a bad application from itself, it can make a good application stand out. So please think about localization in your next marketplace application - your customers will appreciate it!

Gracias. :)

 

Notes:

  • People sometimes ask why the Windows Phone Toolkit (or the Silverlight Toolkit, for that matter) isn't already localized to the same set of languages the host platform supports. While I personally think it should be, doing so would take time and money and those two things can be in rather short supply at times. :) While I hope to see Toolkit localization become official some day, the good news for now is that things have been implemented such that they're easily localizable.

  • I've taken the quick/easy route of assigning the localized text resource directly to PageTitle.Text in the application's constructor, but that is not the recommended technique. Instead, what's generally preferred is what's described in the second half of the "Replacing hard-coded strings with strings in a resource file" section of the MSDN documentation: use a property Binding in XAML to reference the localized resources via a custom object as a StaticResource. It's a little unintuitive at first, but a very reasonable solution in practice. :)

  • After downloading the ZIP file for the Windows Phone Toolkit source code, you should "unblock" it before extracting its contents to avoid warnings from Visual Studio like Security Warning, You should only open projects from a trustworthy source. and The "ValidateXaml" task failed unexpectedly. System.IO.FileLoadException: Could not load file or assembly .... Unblocking is a simple matter of right-clicking on the ZIP file, choosing Properties from the context menu, clicking the Unblock button in the lower, right-hand corner of the resulting dialog, and hitting OK or Apply:

    Unblock button in Properties dialog

Better together [DynamicOrientationChanges and TransitionFrame create a comprehensive transition experience for Windows Phone 7]

I've previously blogged about my implementation of AnimateOrientationChangesFrame, FadeOrientationChangesFrame, and HybridOrientationChangesFrame. As part of my DynamicOrientationChanges sample, these classes smoothly animate an application's layout transition as the phone orientation changes from portrait to landscape (and vice-versa).

HybridOrientationChanges sample

 

More recently, I blogged about the Windows Phone Toolkit's support for animated page transitions. The TransitionFrame class (and its helpers) work with the platform's navigation framework to animate the transitions among different pages within an application.

TransitionFrame sample

 

Though they address different scenarios, both transition helpers make it easy for developers' Silverlight applications to match the behavior of the core Windows Phone 7 applications. The obvious question is whether it's possible to use them together...

At first glance, the fact that both approaches work by directly subclassing PhoneApplicationFrame means they can't be combined as-is.

Aside: This is one of the drawbacks of subclassing as a method of adding or extending functionality in a library: you only get one chance to subclass the base class. (But because you can create as many subclasses as you want, subclassing a subclass can be an excellent alternative!)

So it has always been my hope that these two approaches could be easily combined to create an application that animates both kinds of transitions. Because the Windows Phone Toolkit's TransitionFrame class is more official, it seems appropriate to leave that one alone and try subclassing the DynamicOrientationChanges classes from TransitionFrame. Based on what I knew about both implementations, I assumed this would work, but I didn't get around to trying it before Andy Wigley contacted me with the same question! Well, Andy was brave enough to give this a go and reports that it works well - he wrote a nice summary here:

Best of breed Page rotation animations

If you're interested in combining these two scenarios, I highly recommend checking out Andy's post - he's made the change easy to understand and the steps are easy to follow!

Thanks, Andy! :)

 

PS - If others have success merging the two transition animation implementations, I'll go ahead and make this an official part of the DynamicOrientationChanges project in a future release. Please don't be shy - give it a try and let me know how it goes!

You've got questions; I've got dumb looks [PDC10's Channel 9 Live Windows Phone 7 Q&A session available online and offline]

A few weeks ago, Microsoft held its annual Professional Developer's Conference (PDC10) and I had the privilege of being a (small!) part of it. This year's content spanned a variety of topics, including Windows Azure, HTML 5, Windows Phone 7, and more! The Channel 9 folks were there in force with two full days of live interviews - including a session on Windows Phone 7 Questions & Answers. Under the expert direction of Dan Fernandez, team members Jeff Wilcox, Peter Torr, and myself spent about 30 minutes talking about building Windows Phone 7 applications and answering questions from the (virtual) audience. It was a lot of fun, and I'd like to think it might even be educational! :)

 

Channel 9 Windows Phone 7 Question and Answer session

 

Here are the viewing options:

 

While you're at it, please check out some of the other PDC10 content online - there's a ton of good stuff and it's all free to enjoy!

ListPicker? I hardly even know 'er! [A detailed overview of the Windows Phone Toolkit's ListPicker control]

In yesterday's post, I announced the second release of the Silverlight for Windows Phone Toolkit and gave an overview of the four new controls it includes. (For a discussion of the controls in the original Windows Phone Toolkit, please see my announcement for that release.) In today's post, I want to focus on one of the new controls, ListPicker, and discuss it in detail.

 

The sample application associated with the official Windows Phone Toolkit download offers a great overview of the Windows Phone Toolkit controls, but (deliberately) doesn't get into specific detail on any of them. This post is all about details, so I've written a dedicated sample application which is the source of all the XAML snippets and screenshots below:

[Click here to download the complete source code for the ListPickerSamples application.]

 

Background

From my previous post:

ListPicker is the Windows Phone 7 equivalent of the ComboBox control: give it a list of items and it will show the selected one and also allowing the user to pick from a list if they want to change it. The core applications on Windows Phone 7 implement two kinds of list selection: an in-place expander for picking among five or fewer items, and a full-screen popup for picking among more. The Toolkit's ListPicker control combines both experiences into one handy package by automatically selecting the right UX based on the number of items in its list! It is a standard ItemsControl subclass with all the common elements of a Selector, so the API will be familiar to just about everyone. In fact, you can take most existing ListBoxes and convert them to ListPickers just by changing the control name in XAML!

That's the gist: ListPicker is the control of choice for selecting values in Windows Phone 7 applications. To be more explicit, it is most appropriate in "Settings"-like scenarios where the user is offered a variety of different options and it makes sense to display only the current value (with an option to show everything once the user decides to make a change). Conversely, ListPicker is not appropriate for displaying long lists of data that the user is going to scan and scroll; scenarios like the "People" or "Marketplace" applications are better served by a ListBox or the Windows Phone Toolkit's new LongListSelector.

 

Typical Use

The most common scenario for ListPicker looks something like this:

<StackPanel>
    <toolkit:ListPicker
        Header="Rating"
        ItemsSource="{Binding Ratings}"
        SelectedIndex="1"
        SelectionChanged="RatingSelectionChanged"/>
    <TextBlock
        x:Name="RatingSelection"
        CacheMode="BitmapCache"/>
    ...
</StackPanel>

Which gets displayed like this (in normal and expanded forms):

Typical example (normal) Typical example (expanded)

As you'd expect for an ItemsControl subclass, the ItemsSource property is used to provide the list of items (see also: the Items property). And as you'd expect for a Selector-like control, the SelectionChanged event is used to signal changes and the SelectedIndex property is used to get or set the selection (see also: SelectedItem). Everything so far looks just like ListBox - the only difference is the Header property which can optionally be used to provide a simple, platform-consistent label for the ListPicker that offers additional context about the control's purpose (see also: HeaderTemplate).

Aside: The built-in ListBox control will throw an exception if you set SelectedIndex as in the example above because it tries to apply the selection before the Binding has provided the list of items. ListPicker specifically handles this common scenario so you don't have to jump through hoops to make it work. :)

 

Custom Templates

Displaying strings is all well and good, but sometimes it's nice to display richer content:

Custom template (normal) Custom template (expanded)

The first thing to do is set the ItemTemplate property as you would for ItemsControl or ListBox - that applies the specified DataTemplate to each item and formats it attractively in the usual manner. That works great, but what about ListPicker's Full mode that's used when the list has too many items? By default, the same ItemTemplate automatically applies there, too, so you may not need to do anything more! However, the Full mode UI uses the entire screen, so it's pretty common to want to specifically customize the appearance of the items for that mode. Therefore, the FullModeItemTemplate property lets you provide a different DataTemplate to be used in the Full mode scenario. Another relevant property for such cases is FullModeHeader which sets the content that's shown at the top of the full-screen "popup".

<toolkit:ListPicker
    Header="Spectrum"
    FullModeHeader="CHOOSE COLOR"
    ItemsSource="{Binding Rainbow}"
    ItemTemplate="{StaticResource RainbowTemplate}"
    FullModeItemTemplate="{StaticResource LargeRainbowTemplate}"/>

 

Threshold Overrides

By default, lists with five or fewer items expand in-place while lists with more items switch to a full-screen selection interface. This behavior matches the platform guidelines, but sometimes it might make sense to nudge the threshold one way or another (for very large or very small items, perhaps). You might even want to force a ListPicker to always use Expanded or Full mode...

Threshold (full) Threshold (expanded)

For these scenarios, there's the ItemCountThreshold property: it specifies the maximum number of items that will be displayed in Expanded mode. In addition to nudging it up or down a bit for custom scenarios, it can also be set to 0 to "always use Full mode" or a very large number to "always use Expanded mode". Granted, an application that forces Expanded mode for a list of 1000 items probably won't be easy to use - but the freedom is there to allow developers and designers to dial-in exactly the kind of experience they want.

<toolkit:ListPicker
    Header="Rating"
    FullModeHeader="CHOOSE RATING"
    ItemsSource="{Binding Ratings}"
    ItemCountThreshold="0"/>
<toolkit:ListPicker
    Header="Spectrum"
    ItemsSource="{Binding Rainbow}"
    ItemTemplate="{StaticResource RainbowTemplate}"
    ItemCountThreshold="100"/>

 

Two-Way Binding

Two-way binding

As you'd expect, ListPicker can be used with TwoWay Bindings as well. This is particularly convenient for the SelectedIndex/SelectedItem properties where it's common to want to set the initial value based on a data model (see also: MVVM) and/or when you want the model to update directly when selection changes. The corresponding XAML looks just how you'd expect:

<toolkit:ListPicker
    Header="Network"
    ItemsSource="{Binding Networks}"
    SelectedItem="{Binding CurrentNetwork, Mode=TwoWay}"/>
<StackPanel
    Orientation="Horizontal"
    Margin="{StaticResource PhoneMargin}"
    CacheMode="BitmapCache">
    <TextBlock Text="Current Network: "/>
    <TextBlock Text="{Binding CurrentNetwork}"/>
</StackPanel>

 

Tips and Tricks

At this point, I hope everyone knows how ListPicker works and has a good feel for when/where/why/how to use it. That being the case, there are a few additional things I'd like to draw attention to:

  1. The ListPicker philosophy is that "there is always an active selection", so it makes sure to select an item when it initializes or when the list changes. This automatic selection (of the first item in most cases) causes the SelectionChanged event to fire - and that causes the application's associated event handler to run (assuming one has been registered). In practice, this "initialization-time" event catches some people by surprise - but it's the intended behavior (and folks tend to agree it's correct once they understand why it happens). Now that you know about it, maybe your development experience will be a bit easier. :)

    Aside: If you want to ignore this event in code, it should be easy to detect because its SelectionChangedEventArgs.RemovedItems collection will be empty (have 0 items). And the only time that happens is when ListPicker is transitioning from an empty list to a non-empty one (e.g., on startup).
  2. ListPicker's transitions between Normal and Expanded mode are effectively animations of the control's Height. Because Height changes cause a layout pass, they don't take place on the composition thread and therefore are more susceptible to performance issues. An easy way to mitigate this in the typical "list of items in a StackPanel" scenario is to add CacheMode=BitmapCache to the elements that appear below the ListPicker (i.e., those that are pushed down by the animation). Please refer back to the first XAML snippet for an example - this tweak allows the Silverlight layout system to animate such controls as bitmaps and that helps the animation run a bit more smoothly.

    Aside: If you don't want to apply BitmapCache to every control individually, an alternate approach is to wrap the affected controls in another StackPanel and set the CacheMode property on the StackPanel instead. Please see the last XAML snippet above for an example of this.
  3. If you have a long list of controls in a StackPanel inside a ScrollViewer and there's a ListPicker near the bottom using Expanded mode, that expansion does not automatically scroll the screen to keep the ListPicker completely in view. On WPF, the fix would be a simple matter of calling FrameworkElement.BringIntoView. However, Silverlight doesn't have that API and there doesn't seem to be a good general purpose way for ListPicker to find the right parent to scroll. (Although walking up the visual tree to find the first ScrollViewer is probably right in most cases, it's not a sure thing; ListPicker errs on the side of caution and doesn't try to make guesses.) In practice, the underlying issue doesn't come up very often - when it has, my suggestion has been to use the ItemCountThreshold property to force the relevant ListPicker to use Full mode (which doesn't expand, so it doesn't alter the parent's layout, so it doesn't have this problem).

 

Summary

ListPicker is a relatively straightforward control that should be familiar to anyone who's used the standard ListBox. But while its API may be unremarkable, its user experience is all Windows Phone 7 goodness! :)

I hope you enjoy it!

Mo controls, mo controls, mo controls... [Announcing the second release of the Silverlight for Windows Phone Toolkit!]

I'm happy to report that we've just published the Silverlight for Windows Phone Toolkit November 2010 release! This is the second iteration of the Windows Phone Toolkit and effectively doubles the number of controls we've created to help developers and designers build more compelling, more platform-consistent user experiences with ease. The first Windows Phone Toolkit release has been a big hit and we've seen a lot of developers using it (in both binary and source forms) to build their Windows Phone 7 applications. But while we tried to address the most pressing needs with that release, there were still a couple of prominent controls missing...

With today's update, we've tried to provide more of the fundamental controls customers have been asking for - as well as API documentation and fixes for some of the bugs people reported with the first release. Recall that the Windows Phone Toolkit is published on CodePlex under the Ms-PL open-source license so anyone who wants can look at the source code to learn how we've done things - or customize any control to suit their specific scenario. As always, if you have suggestions for things we should add or change, please search the CodePlex issue tracker and vote for the issue (or create a new one if the idea is unique). We use your input to help prioritize our efforts and ensure we're delivering the right things for the community!

 

What's New?

 

ListPicker

ListPicker sample ListPicker popup sample
<toolkit:ListPicker Header="background">
    <sys:String>dark</sys:String>
    <sys:String>light</sys:String>
    <sys:String>dazzle</sys:String>
</toolkit:ListPicker>

ListPicker is the Windows Phone 7 equivalent of the ComboBox control: give it a list of items and it will show the selected one and also allow the user to pick from a list if they want to change it. The core applications on Windows Phone 7 implement two kinds of list selection: an in-place expander for picking among five or fewer items, and a full-screen popup for picking among more. The Toolkit's ListPicker control combines both experiences into one handy package by automatically selecting the right UX based on the number of items in its list! It is a standard ItemsControl subclass with all the common elements of a Selector, so the API will be familiar to just about everyone. In fact, you can take most existing ListBoxes and convert them to ListPickers just by changing the control name in XAML!

 

LongListSelector

LongListSelector movies sample LongListSelector people sample LongListSelector jump-list sample
<toolkit:LongListSelector
    ItemsSource="{StaticResource movies}"
    ListHeaderTemplate="{StaticResource movieListHeader}"
    GroupHeaderTemplate="{StaticResource movieGroupHeader}"
    GroupFooterTemplate="{StaticResource movieGroupFooter}"
    GroupItemTemplate="{StaticResource groupItemHeader}"
    ItemTemplate="{StaticResource movieItemTemplate}">
</toolkit:LongListSelector>

While ListPicker is about simple selection scenarios, LongListSelector is about advanced ones! Think of it as ListBox++--, it has everything you expect from ListBox plus a bunch of advanced capabilities and great on-device performance minus the levels of abstraction and generality that tend to slow ListBox down. LongListSelector supports full data and UI virtualization, flat lists, grouped lists (with headers!), and also implements the "jump list" header navigation UI that makes the "People" app so efficient! The theory behind LongListSelector is that it should be easy to fix a poorly-performing ListBox scenario by swapping in a LongListSelector instead: it handles all the tricky parts for you, so there's less to worry about and it "just works". Unless you've spent a lot of time fine-tuning your application's list behavior, you should see improved performance by switching to LongListSelector!

 

TransitionFrame (and Transitions)

TransitionFrame sample
RootFrame = new TransitionFrame();
<toolkit:TransitionService.NavigationInTransition>
    <toolkit:NavigationInTransition>
        <toolkit:NavigationInTransition.Backward>
            <toolkit:TurnstileTransition Mode="BackwardIn"/>
        </toolkit:NavigationInTransition.Backward>
        <toolkit:NavigationInTransition.Forward>
            <toolkit:TurnstileTransition Mode="ForwardIn"/>
        </toolkit:NavigationInTransition.Forward>
    </toolkit:NavigationInTransition>
</toolkit:TransitionService.NavigationInTransition>
<toolkit:TransitionService.NavigationOutTransition>
    <toolkit:NavigationOutTransition>
        <toolkit:NavigationOutTransition.Backward>
            <toolkit:TurnstileTransition Mode="BackwardOut"/>
        </toolkit:NavigationOutTransition.Backward>
        <toolkit:NavigationOutTransition.Forward>
            <toolkit:TurnstileTransition Mode="ForwardOut"/>
        </toolkit:NavigationOutTransition.Forward>
    </toolkit:NavigationOutTransition>
</toolkit:TransitionService.NavigationOutTransition>

The Windows Phone UI Guidelines encourage smooth, attractive page-to-page animations like the core applications show, but there has been little platform support for creating similar experiences in your own applications - until now! :) The new transition classes in the Windows Phone Toolkit aims to make it easy for application developers to add attractive, platform-consistent transitions to their applications. All that's necessary to enable transitions for an application's pages is tweak App.xaml.cs (shown above) and add a bit of XAML to each page to specify its transitions (also shown above). Everything else is done for you!

Aside: This release includes support for multiple flavors of the following transitions: turnstile, slide, rotate, swivel, and roll. It's also possible to implement custom transitions using the same framework!

 

AutoCompleteBox

AutoCompleteBox sample
<toolkit:AutoCompleteBox
    ItemsSource="{StaticResource words}"/>

AutoCompleteBox first appeared in the Silverlight 2 Toolkit, then later graduated to the Silverlight 3 SDK. Now it's back in the Toolkit - this time for Windows Phone 7! Because phones are about being small and quick to use, simplifying tedious tasks like text input is an important goal. Toward that end, a number of the core applications (like Bing search) make use of auto-completion to predict what the user is typing and save time by allowing them to click on the completed word instead. AutoCompleteBox makes it easy to bring the same convenience to your own applications by taking advantage of a phone-friendly implementation of this popular Silverlight control. By providing a suitable completion list (in any of a variety of ways), users are automatically prompted with the relevant matches as they start typing!

 

API Documentation

CHM file example

The source code for the Windows Phone Toolkit has included full XML Documentation Comments from the beginning, but now we've begun generating a separate CHM file with all the property/method/event comments in a single, easy-to-browse location. The documentation file is automatically installed by the Windows Phone Toolkit installer and a handy link is added to the "Silverlight for Windows Phone Toolkit" folder in the Start Menu. Because we don't have dedicated documentation writers on the Toolkit team, our documentation is a bit on the terse side - but the CHM file is still a great way to survey the Toolkit classes and get a feel for what's available. And because the sample syntax is available in both C# and VB, everyone should be comfortable with the examples!

 

Bug fixes for existing controls

The previous Toolkit release wasn't all that long ago and we've been quite busy since then, but we've still managed to squeeze in fixes for some of the more annoying bugs customers reported. That's not to say that we fixed them all or that we had a chance to squash your favorite bug, but we were fortunate to be able to fix a good number of customer-impacting issues and I hope everyone finds the new controls even more pleasant to use! :)

 

[Click here to download the Silverlight for Windows Phone Toolkit November 2010 release.]

 

The screen shots and XAML shown above are all from the sample application you can download along with the Toolkit. I encourage people to play around with the sample if they want to experiment with any of these controls (in the emulator or on the device) or if they want to learn more about how these controls work. I anticipate more in-depth coverage will show up in the coming weeks (I will be posting a detailed ListPicker overview tomorrow!), but for now the sample application is a great springboard to get folks started!

 

In closing, I'm really glad we've been able to get this second round of controls out to the community in such a short time! While there are probably still some "nice to have" controls that could be added to further round-out the Windows Phone 7 control offering, I think that what we've included in the Windows Phone Toolkit represents nearly all the critical ones needed to unblock important scenarios. I hope people continue to enjoy their Windows Phone development experience and that the new Windows Phone Toolkit makes application development even easier! :)

There are lots of ways to ask for a date [Creating custom DatePicker/TimePicker experiences is easy with the Windows Phone Toolkit]

DatePicker and TimePicker sample picker

In my previous post announcing the release of the Windows Phone Toolkit, I explained the motivation for the PhoneApplicationPage-based design of the DatePicker and TimePicker controls. Though justified, the current implementation is fairly unusual and has the potential to trip people up if they're not ready for it. So I highly recommend reading the details at the end of that post if you're using DatePicker or TimePicker.

[Waits patiently...]

Okay, if you read the notes, then you understand what we've done and why. And while I'm happy to discuss the pros and cons of the current implementation, that's what we've got for now and I'm going to spend a little time highlighting its extensibility!

 

As with the rest of the Phone Toolkit, our primary goal was to make it easy for developers to match the core Windows Phone 7 experience in their own applications. Toward that end, adding an instance of DatePicker or TimePicker to a page gives the same "small button expands to full-page date/time picker with infinite scrolly thingies" experience that's found in the core Settings, Calendar, and Alarms applications. But sometimes you want to do things a little differently, and maybe you've got a date/time picking interface in mind that's more relevant to your scenario...

 

Aside: If what you want to do is change the format used to display the date/time on the face of the initial "button", then all you need to do is set the ValueStringFormat property to the standard date and time format string or custom date and time format string of your choice!

But because format strings include "{" and "}", they're a little tricky to code in XAML; you need to escape the special characters. here's an example of what this looks like in its simplest form: ValueStringFormat="{}{0:d}"

And here are a few practical examples (using the culture settings for USA):

Description XAML Sample
Short date format (DatePicker default) "{}{0:d}" 9/20/2010
Short time format (TimePicker default) "{}{0:t}" 4:00 PM
Long date format "{}{0:D}" Monday, September 20, 2010
Long time format "{}{0:T}" 4:00:00 PM
Explicit month/day/year format "{}{0:MM-dd-yyyy}" 09-20-2010
Explicit 24-hour time format with text "{}The 24-hour time is {0:HH:mm}." The 24-hour time is 16:00.

 

Customizing the full-screen picker page is as simple as setting the DatePicker.PickerPageUri or TimePicker.PickerPageUri property to point to a PhoneApplicationPage that implements the IDateTimePickerPage interface. The PickerPageUri property uses the standard assembly-relative syntax ("/assemblyShortName;component/resourceLocation"), so it should be familiar to most folks. The IDateTimePickerPage interface is a new interface, but I think you'll agree it's pretty basic:

namespace Microsoft.Phone.Controls.Primitives
{
    /// <summary>
    /// Represents an interface for DatePicker/TimePicker to use for communicating with a picker page.
    /// </summary>
    public interface IDateTimePickerPage
    {
        /// <summary>
        /// Gets or sets the DateTime to show in the picker page and to set when the user makes a selection.
        /// </summary>
        DateTime? Value { get; set; }
    }
}

 

When it's time to display the picker page, DatePicker and TimePicker navigate to the page specified by PickerPageUri via the NavigationService.Navigate("...") method, wait for the page to load, get a reference to its IDateTimePickerPage interface, and set its Value property to the starting DateTime. After that, the custom picker page is in complete control and can display any UI it wants. When the custom picker is done (either because the user picked a date/time or because the user cancelled the operation), the picker should set its Value property to the selected date/time (or null if cancelled) and then call NavigationService.GoBack to return to the previous page. DatePicker and TimePicker automatically detect this, update their own Value property (which automatically updates their UI), and fire their ValueChanged event.

In some ways, it's actually kind of elegant! :) And the fact that the picker is entirely implemented by its own PhoneApplicationPage makes it really easy to work with at design-time in Visual Studio and Blend.

 

To help illustrate the process, I created a sample application that uses custom pickers for DatePicker and TimePicker which let the user pick times relative to the current time:

CustomDateTimePickerPage sample application Custom DatePickerPage example Custom TimePickerPage example

The sample application shows the current date and time because what the emulator reports isn't always the same as what the host operating system reports! In my experience, it's often an hour or more off - so please keep in mind that the times used by the sample are relative to emulator time!

 

Here's the XAML for the main page that hosts the DatePicker and TimePicker controls:

<toolkit:DatePicker
    Value="10/10/2010"
    Header="Custom Date Picker Page"
    PickerPageUri="/CustomDateTimePickerPage;component/CustomDatePickerPage.xaml"/>

<toolkit:TimePicker
    Value="{x:Null}"
    Header="Custom Time Picker Page"
    PickerPageUri="/CustomDateTimePickerPage;component/CustomTimePickerPage.xaml"/>
Aside: Just for fun, I've explicitly set the Value properties here. Although the controls' default behavior of using the current date/time is likely to be what you want most of the time, applications are free to override the initial date/time (as DatePicker does above) or to provide a blank starting value (as TimePicker does with the x:Null markup extension).

 

The implementation of the custom PhoneApplicationPage implementation is so basic, I'm going to show the complete date picker here! (The custom time picker implementation is nearly identical.) I've highlighted the particularly interesting bits, but by now they should be familiar.

First the XAML, then the code:

<phone:PhoneApplicationPage
    x:Class="CustomDateTimePickerPage.CustomDatePickerPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="PortraitOrLandscape" Orientation="Portrait"
    mc:Ignorable="d" d:DesignHeight="800" d:DesignWidth="480">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <TextBlock
            Text="CHOOSE CUSTOM DATE"
            Margin="12"
            FontWeight="Bold"/>

        <StackPanel
            Grid.Row="1"
            VerticalAlignment="Center">
            <Button Content="Tomorrow" Click="TomorrowButtonClick"/>
            <Button Content="Next Week" Click="NextWeekButtonClick"/>
            <Button Content="Next Month" Click="NextMonthButtonClick"/>
            <Button Content="[Cancel]" Click="CancelButtonClick"/>
        </StackPanel>
    </Grid>

</phone:PhoneApplicationPage>
public partial class CustomDatePickerPage : PhoneApplicationPage, IDateTimePickerPage
{
    /// <summary>
    /// Gets or sets the DateTime value for the IDateTimePickerPage interface.
    /// </summary>
    public DateTime? Value { get; set; }

    public CustomDatePickerPage()
    {
        InitializeComponent();
    }

    private void TomorrowButtonClick(object sender, RoutedEventArgs e)
    {
        ChooseDate(DateTime.Now.AddDays(1));
    }

    private void NextWeekButtonClick(object sender, RoutedEventArgs e)
    {
        ChooseDate(DateTime.Now.AddDays(7));
    }

    private void NextMonthButtonClick(object sender, RoutedEventArgs e)
    {
        ChooseDate(DateTime.Now.AddMonths(1));
    }

    private void ChooseDate(DateTime date)
    {
        // Commit date and close picker
        Value = date;
        NavigationService.GoBack();
    }

    private void CancelButtonClick(object sender, RoutedEventArgs e)
    {
        // Cancel selection and close picker
        Value = null;
        NavigationService.GoBack();
    }
}

 

As you can see, creating a custom picker page for DatePicker and TimePicker is really easy! As long as you play by a few basic rules, you have complete freedom to style the entire picker experience in a self-contained, interactive, designer-friendly way. It's kind of like re-Templating - but easier and more flexible - in a weird kind of way!

 

[Click here to download the complete source code for the CustomDateTimePickerPage sample application.]

 

Now get to it - I'm looking forward to seeing the kinds of custom picker experiences you all come up with! :)

See how we make the sausage [Episode 5 of the Inside Windows Phone show highlights the Windows Phone Toolkit!]

If you happen to have 11 minutes, 2 seconds lying around and don't know what to do with yourself, you might consider watching or listening to episode 5 of the Inside Windows Phone show on Channel 9. Of course, I'm a bit biased - this episode features Dave Relyea and I talking about the new controls in the Silverlight for Windows Phone Toolkit we just released. Dave and I were two of the four people who created the Phone Toolkit (the others being Scott Morrison and Will Faught) and were fortunate to be invited by Jaime Rodriguez to talk about it on Channel 9. (If you've never seen a Channel 9 video, it's informal and off-the-cuff. No script and no re-takes - at least for us!)

 

Without further ado, here's Inside Windows Phone #05:Windows Phone Silverlight Toolkit:

Dave, David, and Jaime

 

If you enjoyed that, you might also enjoy Inside Windows Phone #06: Panorama and Pivot are in the house! Woohoo!! which covers the new Windows Phone Panorama and Pivot controls. This was another project Dave Relyea, Scott Morrison, and I were involved in - along with Jeff Wilcox (who's featured in the video).

Thanks a lot to Jaime and the Channel 9 folks for creating these videos. I hope you find them useful - or at least entertaining! :)

Pining for Windows Phone 7 controls? We got ya covered! [Announcing the first release of the Silverlight for Windows Phone Toolkit!]

Phone Toolkit Sample Application

Today marks the official release of the Windows Phone Developer Tools. This free download enables anyone to create .NET applications for the Windows Phone 7 platform using the Silverlight framework (for traditional applications) or the XNA framework (for games). The Windows Phone 7 application development experience is fully integrated with Visual Studio 2010 and Blend 4 and also includes an emulator for running and testing applications without having a phone. It's really cool stuff, and I encourage everyone to learn more about Windows Phone 7 development!

Congratulations to the Windows Phone 7 team on their accomplishment!

 

To celebrate, there's a new download for the Silverlight Toolkit CodePlex project: the Silverlight for Windows Phone Toolkit September 2010 release! Yes, that's right - in addition to providing controls for Silverlight developers targeting the desktop, we're also providing controls for Silverlight developers targeting Windows Phone 7! As you might guess, the Windows Phone Toolkit is a lot like the Silverlight Toolkit: the goal is still to provide a set of controls that complement the platform's core offering and help developers/designers create more compelling, more platform-consistent user experiences simply and easily. Because we focus on writing solid, reusable controls that address common scenarios, you are free to focus on delivering an engaging, compelling application to your customers!

As with the Silverlight Toolkit, the Windows Phone Toolkit comes with full source code (under the permissive OSI-approved Ms-PL license) to help people learn the techniques behind developing rich, platform-consistent controls, to see how we solved a particular problem, or to make tweaks and improvements to the controls themselves! The idea is to publish the Windows Phone Toolkit every few months or so; each release will include new controls, improvements to existing controls, and fixes for any bugs people run into. If you have a suggestion for something we should add or change, please search for that issue in the CodePlex issue tracker and vote for it (or create a new issue if your idea is unique). We pay attention to the number of votes an issue has when prioritizing our efforts - it helps ensure we're delivering what the community wants!

 

Okay, after all that intro and background, you're probably wondering what's actually in the Phone Toolkit... :)

 

What's in the Phone Toolkit?

ContextMenu and ContextMenuService

ContextMenu sample

In desktop applications, ContextMenu is handy because it lets the second mouse button perform additional, contextually-relevant tasks; but on the phone, it's practically a requirement! Phone-sized UIs need to use every pixel to its fullest advantage, so being able to hide secondary commands behind a tap+hold gesture is a great way to keep the interface clean and easy to read.

The Windows Phone Toolkit's ContextMenu control is a direct port of the Silverlight 4 Toolkit's ContextMenu (read more about what it does and how it works here) with additional Windows Phone-specific functionality added on top. So the Phone ContextMenu uses the same, great 100% Silverlight- and WPF-compatible ItemsControl-based API you know and love - plus it looks good on the phone and behaves just like the system's ContextMenu does! Which means ContextMenu (along with its helper ContextMenuService) is simple to use and makes it easy for Windows Phone applications to maintain platform-consistent appearance and behavior. (And for advanced scenarios, ContextMenu supports the ICommand interface, data-binding (of and to) items, Separator, and more!)

Here's the XAML for the example above:

<Border
    Background="{StaticResource PhoneChromeBrush}"
    Padding="20">
    <toolkit:ContextMenuService.ContextMenu>
        <toolkit:ContextMenu>
            <toolkit:MenuItem
                Header="gray text"
                Click="MenuGrayTextClick"/>
            <toolkit:MenuItem
                Header="normal text"
                Click="MenuNormalTextClick"/>
        </toolkit:ContextMenu>
    </toolkit:ContextMenuService.ContextMenu>
    <TextBlock
        x:Name="MenuTextBlock"
        Text="Tap and hold for ContextMenu"
        HorizontalAlignment="Center"/>
</Border>

 

DatePicker and TimePicker

DatePicker and TimePicker sample buttons DatePicker and TimePicker sample picker

Windows Phone 7 includes a cool, distinctive UI for choosing dates and times: three vertical spinners create a fun "endless looping" experience that people really enjoy using. The Phone Toolkit's DatePicker and TimePicker controls implement the exact same experience as the core controls, so it's easy to add date and time selection to your own application!

What's more, these controls are both culture-aware and automatically configure themselves according to the settings on the user's phone (ex: d/m/y vs. m/d/y date formats and 12- vs. 24-hour time format). The API for DatePicker and TimePicker will be familiar to anyone who's used similar "picker" controls in the past. The Header convenience property simplifies the task of labeling either control - in a platform-consistent font and style!

Here's the XAML for the example above and to the right:

<toolkit:DatePicker
    Header="Date"
    Value="9/16/2010"
    ValueChanged="DatePickerValueChanged"/>
<toolkit:TimePicker
    Header="Time"
    Value="12:34 pm"
    ValueChanged="TimePickerValueChanged"/>

 

ToggleSwitch

ToggleSwitch sample

The Windows Phone UI for toggling settings on and off will be immediately familiar to anyone who's used a light switch (or an iDevice). Because there are subtleties to the core controls that are tricky to get right, the Toolkit includes the ToggleSwitch control! Continuing the theme of "make it easy to match the core behavior", ToggleSwitch looks, feels, and acts just like Windows Phone users will expect - including supporting flicks and swipes. In addition to subclassing ToggleButton for consistency and usability, ToggleSwitch supports the Header convenience property to make it easy to create properly-spaced settings pages. And if the need arises, you can also provide custom Content or pull the ToggleSwitchButton primitive control out and use it directly!

Here's the XAML for the example above:

<toolkit:ToggleSwitch
    Header="Some feature"
    IsChecked="true"
    Checked="ToggleSwitchChanged"
    Unchecked="ToggleSwitchChanged"/>

 

GestureListener and GestureService

GestureService and GestureListener sample

Touch interfaces are a lot more interactive and engaging than the conventional mouse+keyboard UI most people are used to. One of the neatest things about touch UIs are their ability to translate natural human gestures into meaningful commands. Taking good advantage of touch and gestures can significantly improve the user experience and really help an application stand out from the crowd.

To make gestures easy to work with, the Phone Toolkit includes the GestureService and GestureListener classes which provide events for the following gestures: tap, double-tap, hold, flick, drag (started/delta/completed), and pinch (started/delta/completed). All these gestures respect the relevant system parameters (ex: movement threshold, input timing, etc.), so applications that use GestureListener feel familiar and natural. All the developer needs to do is associate a GestureListener with the element(s) of interest and handle the corresponding gesture event(s) as they show up!

For more background on gestures, here's a nice, easy to visualize overview for Windows 7 (not identical, but close) and here's a detailed document specific to windows Phone 7.

Here's the XAML for the example above (note that typical applications will only hook up to the event(s) they care about):

<Border
    Background="{StaticResource PhoneChromeBrush}"
    Padding="40">
    <toolkit:GestureService.GestureListener>
        <toolkit:GestureListener
            Tap="GestureListenerTap"
            DoubleTap="GestureListenerDoubleTap"
            Hold="GestureListenerHold"
            Flick="GestureListenerFlick"
            DragStarted="GestureListenerDragStarted"
            DragDelta="GestureListenerDragDelta"
            DragCompleted="GestureListenerDragCompleted"
            PinchStarted="GestureListenerPinchStarted"
            PinchDelta="GestureListenerPinchDelta"
            PinchCompleted="GestureListenerPinchCompleted"/>
    </toolkit:GestureService.GestureListener>
    <TextBlock
        x:Name="GestureTextBlock"
        Text="Perform any gesture here"
        HorizontalAlignment="Center"/>
</Border>

 

WrapPanel

WrapPanel sample

It may not be the sexiest of the Panel classes, but WrapPanel is a tremendously useful layout container! Lots of Windows Phone developers have been using this control from the Silverlight 3 Toolkit (either by referencing that assembly or by copying the code into their projects), but that can be a little tricky - so we thought we'd make it super easy by including WrapPanel in the Phone Toolkit! WrapPanel's "put as much stuff on a line as fits, then wrap to the next line" approach works particularly well on the phone - especially for scenarios where the sizes of things can vary (ex: during the transition from portrait orientation to landscape).

Here's the XAML for the example above:

<toolkit:WrapPanel>
    <Button Content="Here"/>
    <Button Content="is"/>
    <Button Content="some"/>
    <Button Content="simple"/>
    <Button Content="content"/>
    <Button Content="that"/>
    <Button Content="wraps"/>
    <Button Content="to"/>
    <Button Content="fit"/>
    <Button Content="the"/>
    <Button Content="screen"/>
</toolkit:WrapPanel>

 

[Click here to download the sample application used to create all the examples shown here.]

 

Helpful Hints for Hopeful Heroes

Here are a few tips and tidbits to help fledgling Windows Phone 7 developers make the most of the Phone Toolkit:

  • The examples I show here are from my own (deliberately simple) sample application, but there's also a more comprehensive sample application that shows off more sophisticated scenarios. The complete source code for the entire Phone Toolkit (including the sample application) can be downloaded from the CodePlex release page or the CodePlex source code page or by using any of the supported version control system clients (ex: TFS, SVN, etc.).

  • Some (but not all) of the ContextMenus used by the core phone applications get a little fancy when they show the menu: they shrink the UI of the rest of the application in the background. Because we strive to help developers create consistent applications, the Toolkit's ContextMenu does this by default as well.

    But because it's not part of the application itself, our ContextMenu's behavior needs to be as self-contained as possible - which means it can not modify the existing visuals in order to create this effect. (Otherwise it might make an unexpected change that crashes the developer's application!) Therefore, the "shrink" effect is implemented by capturing a "background" screen shot of the entire application, layering it over an opaque PhoneBackgroundBrush layer to avoid transparent areas leaking through, creating a "active element" screen shot capture of just the element that was tap+held, layering this over a correspondingly-sized opaque PhoneBackgroundBrush layer (to avoid transparency issues again), creating a "menu" layer for the actual menu items, layering everything over the running application by putting it in a Popup, and finally animating the scale of the "background" layers. Whew - if that sounds like a lot of effort, it is... :)

    The good news is this works pretty well in practice and duplicates the core effect fairly authentically - the less good news is that certain page designs poke little holes in the sleight-of-hand ContextMenu is doing. In many cases, such issues can be resolved by modifying the target element (the one to which the ContextMenu is attached) to have a non-transparent background. (ContextMenu's PhoneBackgroundBrush guess is the best it can do, but the application developer can sometimes do better.)

    But if you still can't get the effect you're looking for - or if you just don't like the default "shrink and grow" behavior (the core applications don't use it everywhere, either!) - then you can set the (Phone-specific) ContextMenu.IsZoomEnabled property to false in order to disable the custom animation and get rid of all this goofy complexity. In every case I know of so far, developers who resorted to IsZoomEnabled were quite happy with the results! :)

  • Icon configuration When you first add DatePicker or TimePicker to your application, you'll find that the "done" and "cancel" ApplicationBar icons shown when the pickers are opened are wrong. That's because the icons aren't actually being loaded - and that's because of a platform restriction. Specifically, the ApplicationBarButton.IconUri property will only load images that are part of the project and marked with Build Action=Content in the property editor. This means there's no good way for an assembly like the Phone Toolkit assembly to bundle such icons within itself (like there would be if the IconUri property supported the assembly-relative syntax "/assemblyShortName;component/resourceLocation").

    As a result, it's necessary for application developers to add these two icons to a well-known path in their project where DatePicker and TimePicker will automatically use them. For your convenience, we've bundled these two icons along with the Toolkit installer and they're already on your machine! :) To find them, open the Start Menu, expand the "Microsoft Silverlight for Windows Phone Toolkit" folder, and click on the "Binaries" item. This will open a Windows Explorer view of the install location of the Phone Toolkit (something like C:\Program Files\Microsoft SDKs\Windows Phone\v7.0\Toolkit\Sep10\Bin). The icons can be found in the "Icons" sub-folder within.

    To use these two icons in an application, right click the application's project node in the Visual Studio Solution Explorer, choose "Add", choose "New Folder", and rename it "Toolkit.Content". Then right-click on the new folder, choose "Add", choose "Existing Item...", navigate to the Phone Toolkit's install directory, select both icons, and hit "OK". Right-click each icon and change its "Build Action" to "Content"; re-run the application, and they'll show up just like you expect! (And if any of that seemed confusing, just look at how the sample application is configured - match that and you'll be fine.)

  • If you already know Windows Phone 7 supports different themes ("Light" and "Dark", AKA "white background" and "black background"), you might wonder why it's not necessary to provide "Light" and "Dark" versions of each icon... Well, the platform's a little clever here - it will automatically "Light"-ify "Dark" icons when the "Light" theme is active. Therefore, all we need to do is provide is "Dark" versions of the icons - the system converts them for us!

    Note: The reverse is not true; "Light" icons will not be "Dark"-ified for you. (So it seems like maybe the "Dark" side is more powerful?)
  • We've already discussed the reasons why it's good for controls to use the Popup control (because it keeps things isolated from the rest of the application), so DatePicker and TimePicker obviously use Popup too, right? Wrong! :)

    To be fair, DatePicker and TimePicker originally used a Popup for exactly those reasons. And life was good. Except when you tried to scroll the time/date spinners in the picker view... It worked okay, but the frame-rate was pretty low - almost as if the animations weren't happening on the composition (render) thread like they were supposed to... And, indeed, they weren't! It turns out the phone platform doesn't apply hardware acceleration to content in a Popup. :(

    Enough people were unhappy with the performance that DatePicker and TimePicker were modified to use a PhoneApplicationPage-based model instead. What this means is that instead of opening a Popup to hold the picker's spinner UI, these controls instead call NavigationService.Navigate("...") and point it to a Page subclass that's hosted in the same control assembly. The platform doesn't care where it loads pages from, so it happily navigates to the new Page, which then loads the spinners, which benefit from hardware acceleration, and therefore scroll smoothly!

    If this sounds like a wonderful solution, that's because it is - mostly. The big drawback to the Page-based approach is that it subtly breaks one of the guidelines of control development we discussed above: don't make changes that affect the application. In this case, if the application is already listening to the NavigationService's Navigating or Navigated events, then it will also see the "hidden" navigations that DatePicker and TimePicker are performing.

    Whether this is a problem or not depends on what the application is doing and how it's doing it. The good news is that most applications don't track navigations and won't need to worry about this at all; for applications that do track navigations, the good news is that this scenario is easy to detect. Specifically, if the object exposed by NavigationEventArgs.Content during a navigation implements IDateTimePickerPage, then the current navigation is part of DatePicker or TimePicker's behavior and should be ignored by the application. Applications that follow that simple guideline should be safe; applications that ignore it and play tricks like cancelling DatePicker and TimePicker navigations will most likely break stuff. :(

  • Now that I've thoroughly scared everyone away from ever using Page-based navigations, let me back-pedal a bit and say that there are some cool things you can do with them! In particular, DatePicker and TimePicker allow you to customize their destination Page which lets you completely change the picker experience for both of them. But I've already gone on long enough here; that'll be the topic of a subsequent blog post... :)

 

We've had a lot of fun building the Silverlight for Windows Phone Toolkit - and we hope you have a lot of fun using it! Everything in the Phone Toolkit is there because there was strong customer demand. The Silverlight Toolkit team has heard you loud and clear, and we're doing our best to make your Windows Phone 7 development experience as pleasant and productive as possible!

Okay, enough chatter for now - go download the developer tools and get busy building great applications! :)